<template>
  <el-form label-width="60px" :model="account" ref="formRef" :rules="rules">
    <el-form-item label="账号" prop="name">
      <el-input v-model="account.name"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="account.password" type="password"></el-input>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, defineExpose } from 'vue'
import { useStore } from 'vuex'

import type { ElForm } from 'element-plus'
import { rules } from '../config/config'
import localCache from '@/utils/cache'

const store = useStore()

const account = reactive({
  name: localCache.getCache('name') ?? '',
  password: localCache.getCache('password') ?? ''
})

const formRef = ref<InstanceType<typeof ElForm>>()
const loginAction = (isKeepPsw: boolean) => {
  formRef.value?.validate((valid) => {
    // 表单校验
    if (valid) {
      // 1.判断是否要记住密码
      if (isKeepPsw) {
        // 本地缓存账号密码
        localCache.setCache('name', account.name)
        localCache.setCache('password', account.password)
      } else {
        // 删除本地缓存
        localCache.deleteCache('name')
        localCache.deleteCache('password')
      }
      store.dispatch('login/accountLoginAcction', { ...account })
    } else {
      return false
    }
  })
}
defineExpose({
  loginAction
})
</script>

<style scoped></style>
